package day20171010;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by 14394 on 2017/10/11.
 */
public class InitDB {
    private String DBDriver;
    private String user;
    private String password;
    private String url;
    private Connection connection;


    private Statement statement;
    private ResultSet rSet;
    private static final InitDB INIT_DB = new InitDB();//获得数据库连接的静态实例；

    public Statement getStatement() {
        return statement;
    }

    public Connection getConnection() {
        return connection;
    }

    public ResultSet getrSet(String sql) {
        if (sql.toLowerCase().indexOf("select") != -1) {
            try {
                rSet = (ResultSet) statement.executeQuery(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rSet;
    }

    public static InitDB getInitDb() {
        return INIT_DB;
    }

    public InitDB() {
        DBDriver = "com.mysql.jdbc.Driver";
        url = "jdbc:mysql://127.0.0.1:3306/webSpider?userUnicode=true&characterEncoding=utf-8";
        user = "root";
        password = "123456";
        try {
            Class.forName(DBDriver);
            //驱动包与jdk中的jdbc代码的交接
            connection = (Connection) DriverManager.getConnection(url, user, password);
            statement = (Statement) connection.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    public void closeDB() {
        try {
            rSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
